package com.csx.ops.service.node;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.yh.csx.bsf.core.http.DefaultHttpClient;
import com.yh.csx.bsf.core.http.HttpClient;
import com.yh.csx.bsf.core.util.ContextUtils;
import com.yh.csx.bsf.core.util.PropertyUtils;
import com.yh.csx.bsf.core.util.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.var;
import org.apache.http.entity.ContentType;

import java.util.List;
import java.util.Map;

@XStreamAlias("NotifyNode")
public class NotifyNode extends ConfigNode {
    @Getter
    @Setter
    @XStreamAlias("Content")
    private String content;
    @Getter @Setter
    @XStreamAlias("Senders")
    private String senders;

    @Override
    public void exec(){
        printParam(content,senders);
        var url = PropertyUtils.getPropertyCache("notify.url","");
        var smsContent = PropertyUtils.getPropertyCache("notify.content","");
        if(StringUtils.isEmpty(smsContent)){
            smsContent=content;
        }
        if(StringUtils.isEmpty(smsContent)){
            smsContent="您没有配置通知内容";
        }
        if(StringUtils.isEmpty(url)) {
            throw new StateException("第三方消息未配置");
        }
        try {
            this.writeLog("发送消息开始");
            Map<String,Object> result=Maps.newHashMap();
            Map<String,String> cotent=Maps.newHashMap();
            result.put("msg_type","text");
            cotent.put("text",smsContent);
            result.put("content",cotent);
            String jsonStr=JSONObject.toJSONString(result);
            for (var sender : senders.split(",")) {
                if (!StringUtils.isEmpty(sender)) {
                    var newUrl=url+sender;
                    String postResult = HttpRequest
                            .post(newUrl)
                            .header("Content-Type","application/json")
                            .body(jsonStr)
                            .execute()
                            .body();
                    this.writeLog("发送响应结果:"+postResult);
                }
            }
            this.writeLog("发送消息完毕");
        }catch (Exception exp){
            throw new StateException("发送消息失败",exp);
        }
    }

    //从子节点设置对应的状态机
    public void setEngine(StateEngine engine){
        super.setEngine(engine);
    }
}
